package cn.com.dhc.danlu.widget.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.widget.holder.OrderShopViewHolder;
import cn.com.dhc.danlu.widget.popup.MerchPricePopupView;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderDetailResponse.OrderDetailBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.OnChangedPromotionInfoResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean.PromotionModelListBean;

import static cn.com.dhc.danlu.R.id.sdv_merch;

public class OrderShopAdapter extends BaseAdapter {
    /**
     * 调用方上下文
     */
    private Context context;
    /**
     * 商品列表
     */
    private List<MerchListBean> merchList = null;

    /**
     * 存储商品ID与已选促销模型之间的映射
     */
    private HashMap<String, OnChangedPromotionInfoResponse> goodsPromotionModelMap = new HashMap<>();
    /**
     * 存储商品ID与已选促销一览模型之间的映射
     */
    // 实际上只用了剩余次数
    private HashMap<String, PromotionModelListBean> goodsPromotionMap = new HashMap<>();

    public OrderShopAdapter(Context context, List<MerchListBean> merchList, HashMap<String, OnChangedPromotionInfoResponse> goodsPromotionModelMap, HashMap<String, PromotionModelListBean> goodsPromotionMap) {
        this.context = context;
        this.merchList = merchList;
        this.goodsPromotionModelMap = goodsPromotionModelMap;
        this.goodsPromotionMap = goodsPromotionMap;
    }

    @Override
    public int getCount() {
        return merchList != null ? merchList.size() : 0;
    }

    @Override
    public Object getItem(int id) {
        return merchList.get(id);
    }

    @Override
    public long getItemId(int id) {
        return id;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        //------------------------------------初始化 ViewHolder
        OrderShopViewHolder merchHolder;
        if (convertView == null) {
            merchHolder = new OrderShopViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_order_shop_merchinfo, null);

            merchHolder.tvNewPrice = (TextView) convertView.findViewById(R.id.tv_new_price);
            merchHolder.tvOldPrice = (TextView) convertView.findViewById(R.id.tv_old_price);
            merchHolder.tv_barcode = (TextView) convertView.findViewById(R.id.tv_barcode);
            merchHolder.sdvMerch = (SimpleDraweeView) convertView.findViewById(sdv_merch);
            merchHolder.tvMerchName = (TextView) convertView.findViewById(R.id.tv_merch_name);
            merchHolder.tvMerchCount = (TextView) convertView.findViewById(R.id.tv_merch_count);
            merchHolder.llGoodsCoupon = (LinearLayout) convertView.findViewById(R.id.ll_goods_coupon);
            merchHolder.vLine = convertView.findViewById(R.id.v_line);
            merchHolder.tvPriceDetail = (TextView) convertView.findViewById(R.id.tv_price_detail);
            convertView.setTag(merchHolder);
        } else {
            merchHolder = (OrderShopViewHolder) convertView.getTag();
        }
        if (merchList == null || merchList.size() < position + 1) {
            return convertView;
        }

        //------------------------------------ViewHolder 赋值
        final MerchListBean merch = merchList.get(position);
        String averagePrice = "";
        String promotionPrice = "";
        String promotionCount = "";

        merchHolder.tvOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        merchHolder.tvNewPrice.setVisibility(View.VISIBLE);
        if (goodsPromotionModelMap.get(merch.getMerchId()) != null && goodsPromotionModelMap.get(merch.getMerchId()).getDiffPrice() != null) {
            String reductionType = goodsPromotionMap.get(merch.getMerchId()).getReductionType();
            String promotionType = goodsPromotionMap.get(merch.getMerchId()).getPromotionType();

            // 限购
            if (promotionType.equals("4")) {
                merchHolder.tvPriceDetail.setVisibility(View.VISIBLE);
                merchHolder.tvOldPrice.setVisibility(View.VISIBLE);
                merchHolder.tvOldPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                promotionPrice = goodsPromotionMap.get(merch.getMerchId()).getLimitRuleList().get(0).getLimitPrice();

                PromotionModelListBean promotion = goodsPromotionMap.get(merch.getMerchId());
                int merchCount = Integer.parseInt(merch.getMerchQuantity());
                int limitTimes = Integer.parseInt(goodsPromotionMap.get(merch.getMerchId()).getLimitRuleList().get(0).getLimitNumber());

                if (limitTimes >= merchCount) {
                    averagePrice = goodsPromotionMap.get(merch.getMerchId()).getLimitRuleList().get(0).getLimitPrice();
                    promotionCount = String.valueOf(merchCount);

                    merchHolder.tvOldPrice.setText("￥" + CommonUtils.fenToYuan(new BigDecimal(merch.getUnitPrice())).toPlainString());
                    merchHolder.tvNewPrice.setText("￥" + CommonUtils.fenToYuan(new BigDecimal(averagePrice)).toPlainString());
                } else {
                    int diffCount = merchCount - limitTimes;
                    BigDecimal limitPrice = new BigDecimal(limitTimes).multiply(new BigDecimal(promotion.getLimitRuleList().get(0).getLimitPrice()));
                    BigDecimal diffPrice = new BigDecimal(diffCount).multiply(new BigDecimal(merch.getUnitPrice()));
                    BigDecimal avgPrice = limitPrice.add(diffPrice).divide(new BigDecimal(merchCount), 3, BigDecimal.ROUND_HALF_EVEN);

                    merchHolder.tvOldPrice.setText("￥" + CommonUtils.fenToYuan(new BigDecimal(merch.getUnitPrice())).toPlainString());
                    merchHolder.tvNewPrice.setText("￥" + CommonUtils.fenToYuan(avgPrice).toPlainString());

                    averagePrice = avgPrice.toPlainString();
                    promotionCount = String.valueOf(limitTimes);
                }
            } else if (!TextUtils.isEmpty(merch.getUnitPrice()) && reductionType.equals("0") && promotionType.equals("1")) {
                // 满减单
                BigDecimal unitSum = new BigDecimal(merch.getUnitPrice());
                BigDecimal diffPrice = new BigDecimal(goodsPromotionMap.get(merch.getMerchId()).getDiffPrice());
                BigDecimal promotionPrices = unitSum.subtract(diffPrice);

                merchHolder.tvNewPrice.setText(context.getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(promotionPrices).toString());
                merchHolder.tvOldPrice.setVisibility(View.VISIBLE);
                merchHolder.tvOldPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                merchHolder.tvOldPrice.setText(context.getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(merch.getUnitPrice())).toString());
            } else {
                // 满减总和其他
                merchHolder.tvOldPrice.setVisibility(View.GONE);
                merchHolder.tvNewPrice.setText(context.getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(merch.getUnitPrice())).toString());
            }

        } else {
            merchHolder.tvOldPrice.setVisibility(View.GONE);
            merchHolder.tvNewPrice.setText(context.getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(merch.getUnitPrice())).toString());
        }
        // 商品条码
        merchHolder.tv_barcode.setText(merch.getMerchBarCode());
        // 商品图片
        merchHolder.sdvMerch.setImageURI(merch.getPicUrl());
        // 商品名称
        merchHolder.tvMerchName.setText(merch.getMerchName());
        // 设置一个标志位 由于父view LinearLayout  不考虑复用情况导致商品ID错乱
        merchHolder.llGoodsCoupon.setTag(merch.getMerchId());
        // 商品数量
        merchHolder.tvMerchCount.setText(merch.getMerchQuantity());
        // 分割线
        if (position == (getCount() - 1)) {
            merchHolder.vLine.setVisibility(View.GONE);
        }

        // TODO: 2017/3/20 控制 tvPriceDetail 的隐藏显示 @lyf #ok
        final String finalPromotionPrice = promotionPrice;
        final String finalPromotionCount = promotionCount;
        final String finalAveragePrice = averagePrice;
        merchHolder.tvPriceDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/3/20 弹出价格详情 @lyf #ok
                OrderDetailBean.MerchListBean merchPriceDetail = new OrderDetailBean.MerchListBean();
                merchPriceDetail.setPicUrl(merch.getPicUrl());
                merchPriceDetail.setMerchSpec(merch.getSpecName());
                merchPriceDetail.setMerchName(merch.getMerchName());
                merchPriceDetail.setMerchCount(merch.getMerchQuantity());
                merchPriceDetail.setMerchBarCode(merch.getMerchBarCode());
                merchPriceDetail.setUnitPrice(merch.getUnitPrice());
                merchPriceDetail.setAveragePrice(finalAveragePrice);
                merchPriceDetail.setPromotionPrice(finalPromotionPrice);
                merchPriceDetail.setPromotionQuantity(goodsPromotionModelMap.get(merch.getMerchId()).getLimitTimesLeft());

                MerchPricePopupView pricePopupView = new MerchPricePopupView(context, merchPriceDetail);
                pricePopupView.showAtLocation(((Activity) context).getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
            }
        });
        return convertView;
    }
}